package com.play.ballen.home.ui

import android.Manifest
import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.util.Log
import android.view.View
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationClientOption
import com.amap.api.location.AMapLocationListener
import com.hjq.toast.ToastUtils
import com.play.ballen.R
import com.play.ballen.databinding.ActivityBottleDetailBinding
import com.play.ballen.event.EventCost
import com.play.ballen.home.adapter.CommentListAdapter
import com.play.ballen.home.dialog.ReportDialogUtils
import com.play.ballen.home.entity.Comment
import com.play.ballen.home.entity.CommentX
import com.play.ballen.home.vm.PLPFragmentVM
import com.play.ballen.im.PvtChatActivity
import com.play.ballen.utils.UserInfoManager
import com.play.ballen.widget.emoji.InputViewHolder
import com.play.ballen.widget.emoji.InterceptFrameLayout.OnInterceptListener
import com.play.ballen.widget.emoji.KeyBoardUtil
import com.yuven.appframework.util.imageloader.ImageUtil
import com.yuven.baselib.component.BaseMVVMActivity
import com.yuven.baselib.component.eventbus.Event
import com.yuven.baselib.component.eventbus.EventBusUtil
import com.yxp.permission.util.lib.PermissionUtil
import com.yxp.permission.util.lib.callback.PermissionResultCallBack
import java.time.OffsetDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Locale


class BottleDetailActivity: BaseMVVMActivity<PLPFragmentVM, ActivityBottleDetailBinding>(),
    AMapLocationListener, KeyBoardUtil.KeyBoardHeightListener {

    var id: Int = 0

    private var mLocationClient: AMapLocationClient? = null //定位发起端
    private var mLocationOption: AMapLocationClientOption? = null //定位参数

    private var longitude = 0.0
    private var latitude = 0.0
    var parent_id = 0//父评论的id, 没有填0
    var target_id = 0//回复某评论填该评论id, 否则填0
    var content = ""
    var cont= ""
    private var mInputViewHolder: InputViewHolder? = null
    private var mKeyBoardUtil: KeyBoardUtil? = null
    private val fragmentManager: FragmentManager = supportFragmentManager
    private val adapter: CommentListAdapter by lazy {
        CommentListAdapter(arrayListOf())
    }
    private val reportDialogUtils by lazy {
        ReportDialogUtils(this).apply {
            valuesCopyCallback = {
                val clipboardManager = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                // 创建一个 ClipData 对象
                val clipData = ClipData.newPlainText("label", it)
                // 将 ClipData 设置到剪贴板
                clipboardManager.setPrimaryClip(clipData)
                ToastUtils.show("复制成功")
            }
            valuesReportCallback = {
                JubaoActivity.start(mContext, it)
            }
            valuesDeleteCallback ={
                viewModel.deleteComment(it.toString())
            }
        }
    }

    override fun registerEventBus(): Boolean {
        return true
    }

    override fun handleEvent(event: Event<Any>) {
        super.handleEvent(event)
        when (event.code) {
            EventCost.REPLY_COMMENT_2 -> {
                //二级评论
                var comment = event.data as CommentX
                parent_id = comment.parent_id
                target_id = comment.id
                mInputViewHolder!!.clearEditText()
                mInputViewHolder!!.setEditHint("回复@"+comment.nickname)
                mInputViewHolder!!.showKeyBoard()
//                CommenKeyboardActivity.start(mContext,id,parent_id,target_id,comment.nickname)
            }
            EventCost.REPLY_COMMENT_Like -> {
                viewModel.likeComment(event.data.toString())
            }
            EventCost.REPLY_COMMENT_UNLike -> {

                viewModel.unLikeComment(event.data.toString())
            }

            EventCost.REFRESH_BOTTLE_DETAIL -> {
                viewModel.seeBottle(id.toString())
            }
            EventCost.ADD_REPORT -> {
                var comment = event.data as CommentX
                var id =  comment.id
                var content =  comment.content
                var phone =  comment.phone
                var delelte =  comment.can_delete
                reportDialogUtils.show(id,content,phone,delelte)
            }

            EventCost.ADD_COMMENT -> {
                viewModel.seeBottle(id.toString())
//                var comment = UserInfoManager.getUserInfo()?.info?.let { Comment(content=event.data as String, post_time = "刚刚", nickname = "我", avatar_url = it.avatar_url) }
//                if (comment != null) {
//                    adapter.addItemAtBeginning(comment)
//                }
            }

        }
    }

    companion object {
        @JvmStatic
        fun start(context: Context, data1: Int) {
            val starter = Intent(context, BottleDetailActivity::class.java)
            starter.putExtra("id", data1)
            context.startActivity(starter)
        }
    }
    override fun initIntent(intent: Intent?) {
        if (intent != null) {
            id = intent.getIntExtra("id",0)
        }
    }



    override fun layoutId(): Int {
        return R.layout.activity_bottle_detail
    }

    override fun viewModelClass(): Class<PLPFragmentVM> {
        return PLPFragmentVM::class.java
    }

    @RequiresApi(Build.VERSION_CODES.O)
    override fun initObserver() {
        super.initObserver()
        viewModel.pImGroup.observe(this) {
            if (it != null) {
                PvtChatActivity.actionStart(mContext,it.room_id)
            }
        }
        viewModel.bottleDetail.observe(this) {
            dataBinding.tvDynamic.text = it.content
            ImageUtil.instance.loadCircleImage(it.avatar,dataBinding.ivHead, 0, 0)

            if(it.image.isNotEmpty()){
                ImageUtil.instance.loadImage(it.image,dataBinding.ivDetail)
                dataBinding.ivDetail.visibility = View.VISIBLE
            }

            if(it.anonymous){
                dataBinding.tvName.text = it.anonymous_nickname
            }else{
                dataBinding.tvName.text = it.nickname
            }
            if(it.is_follow){
                dataBinding.tvFollow.text = "已关注"
            }else{
                dataBinding.tvFollow.text = "关注"
            }
            dataBinding.tvTime.text = convertDateTime(it.post_time)
            adapter.setList(it.comments)
        }

        viewModel.followSuccess.observe(this) {
//            dataBinding.chatMsgInputBox.visibility= View.GONE
            viewModel.seeBottle(id.toString())
        }
        viewModel.deleteSuccess.observe(this) {
            viewModel.seeBottle(id.toString())
        }

        viewModel.actionAddCommentSuccess.observe(this) {
            if (mInputViewHolder != null) {
                mInputViewHolder!!.hideKeyBoardFaceMore()
                mInputViewHolder!!.clearEditText()
                mInputViewHolder!!.setDefaultHint()
            }
            if(parent_id==0&&target_id==0){//发布一级评论
                EventBusUtil.post(
                    Event.create(
                        EventCost.ADD_COMMENT,content))

            }else{
                viewModel.seeBottle(id.toString())
//                EventBusUtil.post(
//                    Event.create(
//                        EventCost.REFRESH_BOTTLE_DETAIL))
            }
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    @RequiresApi(Build.VERSION_CODES.O)
    override fun initView() {
        mInputViewHolder = InputViewHolder(
            mContext,
            findViewById(R.id.input_container) as ViewGroup,
            false, R.layout.view_input_top_active, R.layout.view_input_face
        )
        mInputViewHolder!!.addToParent()
        mInputViewHolder!!.subscribeActivityLifeCycle()
        mInputViewHolder!!.setActionListener(object : InputViewHolder.ActionListener() {
            override fun onSendClick(text: String?) {
                content = text.toString()
//                sendComment(text)
                val map = mutableMapOf<String, Any>()
                map["moment_id"] = id
                map["parent_id"] = parent_id
                map["target_id"] = target_id
                map["content"] = text.toString()
                map["longitude"] = longitude
                map["latitude"] = latitude
                viewModel.addComment(map)

            }
        })
        mKeyBoardUtil = KeyBoardUtil(dataBinding.nest, this)
        dataBinding.tvFollow.setOnClickListener{
            if(viewModel.bottleDetail.value?.is_follow == true){
                viewModel.unfollowBottle(viewModel.bottleDetail.value?.id.toString())
            }else{
                viewModel.followBottle(viewModel.bottleDetail.value?.id.toString())
            }
        }
        dataBinding.groupIntercept.setOnInterceptListener(OnInterceptListener {
            if (mInputViewHolder != null) {
                mInputViewHolder!!.hideKeyBoardFaceMore()
            } else false
        })

        viewModel.seeBottle(id.toString())
        dataBinding.ivBack.setOnClickListener{
            finish()
        }
        dataBinding.tvReport.setOnClickListener{
            viewModel.bottleDetail.value?.let { it1 -> JubaoActivity.start(mContext, it1.id) }
        }
//        dataBinding.tvPinglun.setOnClickListener{
//            parent_id = 0
//            target_id = 0
////            CommenKeyboardActivity.start(mContext,id,parent_id,target_id,"")
//        }
        dataBinding.tvSixin.setOnClickListener{
            viewModel.getGroupIm();
        }
        dataBinding.ivDetail.setOnClickListener{
            viewModel.bottleDetail.value?.let { it1 -> DragImgActivity.start(mContext, it1.image) }
        }
        adapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.getId()) {
                //一级评论
                R.id.huifu -> {
                    parent_id = viewModel.bottleDetail.value?.comments?.get(position)?.id!!
                    target_id = 0
                    mInputViewHolder!!.clearEditText()
                    mInputViewHolder!!.setEditHint("回复@"+ viewModel.bottleDetail.value?.comments?.get(position)?.nickname)
                    mInputViewHolder!!.showKeyBoard()
//                    viewModel.bottleDetail.value?.comments?.get(position)?.nickname?.let {
//                        CommenKeyboardActivity.start(mContext,id,parent_id,target_id,
//                            it
//                        )
//                    }
                }
                R.id.zan_ly -> {
                    if(viewModel.bottleDetail.value?.comments?.get(position)?.is_like == true){
                        viewModel.bottleDetail.value?.comments?.get(position)!!.is_like = false
                        viewModel.bottleDetail.value?.comments?.get(position)!!.like_count-=1
                        adapter.notifyDataSetChanged()
                        viewModel.unLikeComment(viewModel.bottleDetail.value?.comments?.get(position)?.id.toString())
                    }else{
                        viewModel.bottleDetail.value?.comments?.get(position)!!.is_like = true
                        viewModel.bottleDetail.value?.comments?.get(position)!!.like_count+=1
                        adapter.notifyDataSetChanged()
                        viewModel.likeComment(viewModel.bottleDetail.value?.comments?.get(position)?.id.toString())
                    }

                }
            }
        }
        adapter.setOnItemLongClickListener() { _, view, position ->
            var id = viewModel.bottleDetail.value?.comments?.get(position)?.id
            var content = viewModel.bottleDetail.value?.comments?.get(position)?.content
            var phone =  viewModel.bottleDetail.value?.comments?.get(position)?.phone
            var delelte =  viewModel.bottleDetail.value?.comments?.get(position)?.can_delete
            reportDialogUtils.show(id,content,phone,delelte)
            true
        }

    }

    override fun onResume() {
        super.onResume()
        getPermission()
    }

    override fun initData() {
        setStatusbar(R.color.c2e,true)
        dataBinding.commentList.layoutManager =  LinearLayoutManager(mContext)
        dataBinding.commentList.adapter = adapter
    }



    @RequiresApi(Build.VERSION_CODES.O)
    fun convertDateTime(inputDateTime: String): String {
        val formatter = DateTimeFormatter.ofPattern("yyyy.MM.dd EEEE", Locale.SIMPLIFIED_CHINESE)

        val offsetDateTime = OffsetDateTime.parse(inputDateTime)
        val zoneId = ZoneId.of("Asia/Shanghai")
        val zonedDateTime = offsetDateTime.atZoneSameInstant(zoneId)

        return zonedDateTime.format(formatter)
    }

    private fun initLocation() {
        //初始化定位
        try {
            mLocationClient = AMapLocationClient(applicationContext)
            //设置定位回调监听
            mLocationClient!!.setLocationListener(this)
            //初始化定位参数
            mLocationOption = AMapLocationClientOption()
            //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
            mLocationOption!!.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy)
            //设置是否返回地址信息（默认返回地址信息）
            mLocationOption!!.setNeedAddress(true)
            //设置是否只定位一次,默认为false
            mLocationOption!!.setOnceLocation(false)
            //设置是否强制刷新WIFI，默认为强制刷新
            mLocationOption!!.setWifiActiveScan(true)
            //设置是否允许模拟位置,默认为false，不允许模拟位置
            mLocationOption!!.setMockEnable(false)
            //设置定位间隔,单位毫秒,默认为2000ms
            mLocationOption!!.setInterval((6 * 1000).toLong())
            //        mLocationOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
            //给定位客户端对象设置定位参数
            mLocationClient!!.setLocationOption(mLocationOption)
            //启动定位
            mLocationClient!!.startLocation()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onLocationChanged(amapLocation: AMapLocation) {
        if (amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e(
                    "xypError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo()
                )
            }
            longitude = amapLocation.longitude
            latitude = amapLocation.latitude

            Log.e("xyp","longitude= "+longitude)
        }
    }




    private fun getPermission() {
        val PERMISSIONS = arrayOf(
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_FINE_LOCATION
        )
        PermissionUtil.getInstance().request(mActivity, PERMISSIONS,
            object : PermissionResultCallBack {
                override fun onPermissionGranted() {
                    initLocation()
                }

                override fun onPermissionGranted(vararg p0: String?) {
                }

                override fun onPermissionDenied(vararg p0: String?) {
                    toSelfSetting(mActivity)
                    ToastUtils.show("需要打开存储权限")
                }

                override fun onRationalShow(vararg p0: String?) {
                    toSelfSetting(mActivity)
                    ToastUtils.show("需要打开存储权限")
                }

            })
    }

    fun toSelfSetting(context: Context) {
        val mIntent = Intent()
        mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        if (Build.VERSION.SDK_INT >= 9) {
            mIntent.action = "android.settings.APPLICATION_DETAILS_SETTINGS"
            mIntent.data = Uri.fromParts("package", context.packageName, null)
        } else if (Build.VERSION.SDK_INT <= 8) {
            mIntent.action = Intent.ACTION_VIEW
            mIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails")
            mIntent.putExtra("com.android.settings.ApplicationPkgName", context.packageName)
        }
        context.startActivity(mIntent)
    }

    override fun onKeyBoardHeightChanged(keyboardHeight: Int) {
        if (mInputViewHolder != null) {
            mInputViewHolder!!.onKeyBoardHeightChanged(keyboardHeight)
        }
    }

    override fun onBackPressed() {
        if (mInputViewHolder != null && mInputViewHolder!!.hideKeyBoardFaceMore()) {
            return
        }
        super.onBackPressed()
    }
    override fun onDestroy() {
        super.onDestroy()
        if (mKeyBoardUtil != null) {
            mKeyBoardUtil!!.release()
        }
        mKeyBoardUtil = null
    }
}